package api

import (
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/base"
	"cgs-server/server/service"
	"cgs-server/server/store"
	"fmt"
	"net/http"
	"strings"
)

type UploadHandler struct {
	srv service.Service
}

func NewUploadHandler(store store.Factory) *UploadHandler {
	return &UploadHandler{
		srv: service.NewService(store),
	}
}

func (v *UploadHandler) Upload(w http.ResponseWriter, r *http.Request) {
	_ = r.ParseMultipartForm(server.Config.Upload.MaxSize)
	files := r.MultipartForm.File
	mimeType := r.FormValue("type")

	// check upload file
	if len(files) != 1 {
		_, _ = helper.WriteJSON(w, server.Fail("Please select an file"))
		return
	}
	file := files["file"][0]

	user, err := base.GetCurrentUser(r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	result, err := v.srv.Upload().Upload(file, mimeType, user)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	result.Domain = fmt.Sprintf("http://%s%s", strings.Split(r.Host, ":")[0], ":9000")
	_, _ = helper.WriteJSON(w, server.OK("Upload successfully!").WithData(result))
}
